#include <iostream>
#include <string>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"

using namespace httplib;

ns_control::Control *cli_ptr = nullptr;

void Recover(int num)
{
        cli_ptr->RecoverMachine();
}

int main()
{
        // 注册信号  ctrl + \ ：重新上线全部主机
        signal(SIGQUIT, Recover);

        // 用户服务请求的路由功能
        Server svr;
        ns_control::Control ctrl;
        cli_ptr = &ctrl;

        // 设置默认首页
        svr.set_base_dir("./wwwroot");

        // 获取题目列表
        svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
                {
                    std::string html;
                    ctrl.AllQuestions(&html);
                    resp.set_content(html, "text/html;charset=utf-8"); });

        // 获取指定题目以及编辑区
        //(\d+): 正则表达式; matches[0]存放的是资源路径/question/66
        svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp)
                {
                    std::string number = req.matches[1];
                    std::string html;
                    ctrl.OneQuestion(number, &html);
                    resp.set_content(html, "text/html; charset=utf-8"); });

        // 提交题目判定
        svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
                 {
                    std::string number = req.matches[1];
                    std::string result_json;
                    ctrl.Judge(number, req.body, &result_json);
                    resp.set_content(result_json, "application/json; charset=utf-8"); });

        svr.Get("/race", [&ctrl](const Request &req, Response &resp)
                { std::string race_home_path = "./wwwroot/race/race_home.html";
                  std::string html;
                  ctrl.PageSkip(race_home_path, &html);
                  resp.set_content(html, "text/html; charset=utf-8"); });

        svr.Get("/login", [&ctrl](const Request &req, Response &resp)
                { std::string login_home_path = "./wwwroot/login/login_home.html";
                  std::string html;
                  ctrl.PageSkip(login_home_path, &html);
                  resp.set_content(html, "text/html; charset=utf-8"); });

        svr.listen("0.0.0.0", 8080);

        return 0;
}
